/**
 * 作者：风雪涟漪
 * 版本0.2v
 * 上次更新：2009-11-20
 * 更新：
 * 1.增加国际化功能
 * 2.增加隐藏表单方便提交
 * 3.修复CSS下拉菜单位置的BUG
 */

( function($) {

	jQuery.fn.datecontrol = function(options) {
		var defaults = {
			startdate :new Date(),
			enddate :new Date(),
			format :"mm/dd/yyyy",
			word:{
				define:"自定义时间范围",
				today:"今天",
				yestoday:"昨天",
				lastweek:"上周",
				month:"这个月",
				lastmonth:"上个月",
				apply:"应用"
			},
			hiddenStartName:'startdate',
			hiddenEndName:'enddate',
			onApply : function(value, date) {
			}
		}

		var options = $.extend(defaults, options);

		return this.each( function() {
			var i=Math.floor(Math.random()*1000+1);
		
			var o = options;
			// var displayStart = o.startdate;
				// var displayEnd = o.enddate;
				var startDate = o.startdate;
				var endDate = o.enddate;

				var idDateView = 'id_date_view' + i;
				var idDateContent = 'id_date_content' + i;
				var idLastMonth = 'id_last_month' + i;
				var idMonth = 'id_month' + i;
				var idLastWeek = 'id_last_week' + i;
				var idYestoday = 'id_yestoday' + i;
				var idToday = 'id_today' + i;
				var idDefine = 'id_define' + i;
				var idApply = 'id_apply' + i;
				var idDefineInput = "id_define_input" + i;
				var idHiddenStart = "id_hidden_start"+i;
				var idHiddenEnd = "id_hidden_end"+i;
				
				var licontent = "<li  class='li_content'><input id=" + idDefine
						+ " name='selectdate"+i+"' type='radio'></input><span id="
						+ idDefineInput + ">"+o.word.define+"</span></li>"
						+ "<li class='li_content'><input id=" + idToday
						+ " name='selectdate"+i+"' type='radio'></input>"+o.word.today+"</li>"
						+ "<li class='li_content'><input id=" + idYestoday
						+ " name='selectdate"+i+"' type='radio'></input>"+o.word.yestoday+"</li>"
						+ "<li class='li_content'><input id=" + idLastWeek
						+ " name='selectdate"+i+"' type='radio'></input>"+o.word.lastweek+"</li>"
						+ "<li class='li_content'><input id=" + idMonth
						+ " name='selectdate"+i+"' type='radio'></input>"+o.word.month+"</li>"
						+ "<li class='li_content'><input id=" + idLastMonth
						+ " name='selectdate"+i+"' type='radio'></input>"+o.word.lastmonth+"</li>";
				var lisubmit = "<li class='li_content'><input class='btn_b' id=" + idApply
						+ "  type='button' value='"+o.word.apply+"'></input></li>";
				licontent += lisubmit;
				var ulcontent = "<ul id=" + idDateContent
						+ " class='ul_content'>";
				var divdate = "<div id=" + idDateView
						+ " class='view_date'></div>";

				var divdatecontrol = "<div class='date_container'>";
		//		alert(idHiddenStart+idHiddenEnd+hiddenStartName+hiddenEndName+"");
				var hiddenText = "<input id='"+idHiddenStart+"' type='hidden' name='"+o.hiddenStartName+"'/>" +
								"<input id='"+idHiddenEnd+"' type='hidden' name='"+o.hiddenEndName+"'/>";
			//	alert(hiddenText);
				var finalHtml = "<div class='date_container'>" + divdate
				+ ulcontent + licontent+hiddenText+ "</ul></div>";
				$(this).html(finalHtml);
				// init
			
				
				showDisplay(o.startdate, o.enddate);

				$("#" + idDateView).click( function() {
					$("#" + idDateContent).slideToggle('fast');
				});
				// 获取上个月的范围
				$("#" + idLastMonth).click( function() {
					startDate = getLastMonthStart();
					endDate = getMonthEnd(getLastMonthStart());
					showDisplay(startDate, endDate);
					$("#" + idDefineInput).html(o.word.define);
				})

				// 获取这个月的范围
				$("#" + idMonth).click( function() {
					startDate = getMonthStart();
					endDate = getMonthEnd(getMonthStart());
					showDisplay(startDate, endDate);
					$("#" + idDefineInput).html(o.word.define);
				});

				// 获取上周的范围
				$("#" + idLastWeek).click( function() {
					startDate = getLastWeekStart();
					endDate = getLastWeekEnd(getLastWeekStart());
					showDisplay(startDate, endDate);
					$("#" + idDefineInput).html(o.word.define);
				});
				// 获取昨天的范围
				$("#" + idYestoday).click( function() {
					startDate = getYestoday();
					endDate = getYestoday();
					showDisplay(startDate, endDate);
					$("#" + idDefineInput).html(o.word.define);
				});
				// 获取今天的范围
				$("#" + idToday).click( function() {
					startDate = new Date();
					endDate = new Date();
					showDisplay(startDate, endDate);
					$("#" + idDefineInput).html(o.word.define);
				});

				$("#" + idDefine)
						.click(
								function() {
									var idDatePicker = "id_datepicker"+i;
									$("#" + idDefineInput)
											.html(
													"<input type='text' id="+idDatePicker+" class='definedate'></input>");
									$("#"+idDatePicker).val(startDate.format(o.format)+" - "+endDate.format(o.format));
									var dateFormat = o.format;
									
									if (getCharNumber(o.format, "y") == 4) {
										dateFormat = o.format.replace(
												"yyyy", "yy");
									} else if (getCharNumber(o.format, "y") == 2) {
										dateFormat = o.format.replace("yy",
												"y");
									}
									
									$(".definedate")
											.datepick(
													{
														autoSize :true,
														dateFormat :dateFormat,
														rangeSelect :true,
														numberOfMonths :2,
														buttonImageOnly :true,
														onSelect : function(value, date) {
															startDate=date[0];
															endDate=date[1];
															$("#" + idDateView).html(value);
															//$(".definedate").val(value.split("-")[1]);
					                                      //  $(".definedate").val($("#startdate").val()+"-"+$("#enddate").val());
														}
													});
									
								});

				$("#" + idApply).click( function() {
					$("#" + idDateContent).slideUp('fast');
					var value =new Array(startDate.format(o.format),endDate.format(o.format));		
					var date = new Array(startDate,endDate);
					o.onApply(value, date);
				});
				
				
				
				function showDisplay(startdate, enddate) {
			
					$("#" + idDateView).html(
							startdate.format(o.format) + " - "
									+ enddate.format(o.format));
					$("#"+idHiddenStart).val(startdate.format(o.format));
					$("#"+idHiddenEnd).val(enddate.format(o.format));
				}

			});

	};
	function getCharNumber(source, charSet) {
		var i;
		var count = 0;
		for (i = 0; i < source.length; i++) {
			//alert(source[i]);
			if (source.charAt(i) == charSet) {
				
				count = count + 1;
			}
		}
		return count;
	}

	/**
	 * 获取昨天的日期
	 * 
	 * @return
	 */
	function getYestoday() {
		var dt = new Date();
		dt.setDate(dt.getDate() - 1);

		return dt
	}

	/**
	 * 上一周的开始日期
	 * 
	 * @return
	 */
	function getLastWeekStart() {
		var lastWeekStart = new Date();
		if (lastWeekStart.getDay() == 0) {
			lastWeekStart.setDate(lastWeekStart.getDate()
					- lastWeekStart.getDay() - 13);

		} else {
			lastWeekStart.setDate(lastWeekStart.getDate()
					- lastWeekStart.getDay() - 6);
		}
		return lastWeekStart;
	}

	function getLastWeekEnd(lastWeekStart) {
		lastWeekStart.setDate(lastWeekStart.getDate() + 6);
		return lastWeekStart;
	}

	/**
	 * 获取本月的开始日期
	 * 
	 * @return
	 */
	function getMonthStart() {
		var monthStart = new Date();
		monthStart.setDate(1);
		return monthStart;
	}

	/**
	 * 获取上月的开始日期
	 * 
	 * @return
	 */
	function getLastMonthStart() {
		var lastMonthStart = new Date();
		lastMonthStart.setMonth(lastMonthStart.getMonth() - 1, 1);
		return lastMonthStart;
	}
	/**
	 * 获取月末日期
	 */
	function getMonthEnd(monthDate) {
		var lastMonthDay = new Date(monthDate.getFullYear(), monthDate
				.getMonth() + 1, 0);
		return lastMonthDay;
	}

	/**
	 * Date format
	 * 
	 * var now = new Date();
	 * 
	 * now.format("m/dd/yy"); // Returns, e.g., 6/09/07 // Can also be used as a
	 * standalone function dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT"); //
	 * Saturday, June 9th, 2007, 5:46:21 PM // You can use one of several named
	 * masks now.format("isoDateTime"); // 2007-06-09T17:46:21 // ...Or add your
	 * own dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
	 * now.format("hammerTime"); // 17:46! Can't touch this! // When using the
	 * standalone dateFormat function, // you can also provide the date as a
	 * string dateFormat("Jun 9 2007", "fullDate"); // Saturday, June 9, 2007 //
	 * Note that if you don't include the mask argument, //
	 * dateFormat.masks.default is used now.format(); // Sat Jun 09 2007
	 * 17:46:21 // And if you don't include the date argument, // the current
	 * date and time is used dateFormat(); // Sat Jun 09 2007 17:46:22 // You
	 * can also skip the date argument (as long as your mask doesn't // contain
	 * any numbers), in which case the current date/time is used
	 * dateFormat("longTime"); // 5:46:22 PM EST // And finally, you can convert
	 * local time to UTC time. Either pass in // true as an additional argument
	 * (no argument skipping allowed in this case): dateFormat(now, "longTime",
	 * true); now.format("longTime", true); // Both lines return, e.g., 10:46:21
	 * PM UTC // ...Or add the prefix "UTC:" to your mask.
	 * now.format("UTC:h:MM:ss TT Z"); // 10:46:21 PM UTC
	 */
	var dateFormat = function() {
		var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g, pad = function(
				val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len)
				val = "0" + val;
			return val;
		};

		// Regexes and supporting functions are cached through closure
		return function(date, mask, utc) {
			var dF = dateFormat;

			// You can't provide utc if you skip other args (use the "UTC:" mask
			// prefix)
			if (arguments.length == 1
					&& Object.prototype.toString.call(date) == "[object String]"
					&& !/\d/.test(date)) {
				mask = date;
				date = undefined;
			}

			// Passing date through Date applies Date.parse, if necessary
			date = date ? new Date(date) : new Date;
			if (isNaN(date))
				throw SyntaxError("invalid date");

			mask = String(dF.masks[mask] || mask || dF.masks["default"]);

			// Allow setting the utc argument via the mask
			if (mask.slice(0, 4) == "UTC:") {
				mask = mask.slice(4);
				utc = true;
			}

			var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_
					+ "Day"](), m = date[_ + "Month"](), y = date[_
					+ "FullYear"](), H = date[_ + "Hours"](), M = date[_
					+ "Minutes"](), s = date[_ + "Seconds"](), L = date[_
					+ "Milliseconds"](), o = utc ? 0 : date.getTimezoneOffset(), flags = {
				d :d,
				dd :pad(d),
				ddd :dF.i18n.dayNames[D],
				dddd :dF.i18n.dayNames[D + 7],
				m :m + 1,
				mm :pad(m + 1),
				mmm :dF.i18n.monthNames[m],
				mmmm :dF.i18n.monthNames[m + 12],
				yy :String(y).slice(2),
				yyyy :y,
				h :H % 12 || 12,
				hh :pad(H % 12 || 12),
				H :H,
				HH :pad(H),
				M :M,
				MM :pad(M),
				s :s,
				ss :pad(s),
				l :pad(L, 3),
				L :pad(L > 99 ? Math.round(L / 10) : L),
				t :H < 12 ? "a" : "p",
				tt :H < 12 ? "am" : "pm",
				T :H < 12 ? "A" : "P",
				TT :H < 12 ? "AM" : "PM",
				Z :utc ? "UTC" : (String(date).match(timezone) || [ "" ]).pop()
						.replace(timezoneClip, ""),
				o :(o > 0 ? "-" : "+")
						+ pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o)
								% 60, 4),
				S : [ "th", "st", "nd", "rd" ][d % 10 > 3 ? 0 : (d % 100 - d
						% 10 != 10)
						* d % 10]
			};

			return mask.replace(token, function($0) {
				return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
			});
		};
	}();

	// Some common format strings
	dateFormat.masks = {
		"default" :"ddd mmm dd yyyy HH:MM:ss",
		shortDate :"m/d/yy",
		mediumDate :"mmm d, yyyy",
		longDate :"mmmm d, yyyy",
		fullDate :"dddd, mmmm d, yyyy",
		shortTime :"h:MM TT",
		mediumTime :"h:MM:ss TT",
		longTime :"h:MM:ss TT Z",
		isoDate :"yyyy-mm-dd",
		isoTime :"HH:MM:ss",
		isoDateTime :"yyyy-mm-dd'T'HH:MM:ss",
		isoUtcDateTime :"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
	};

	// Internationalization strings
	dateFormat.i18n = {
		dayNames : [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday",
				"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
				"Saturday" ],
		monthNames : [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
				"Sep", "Oct", "Nov", "Dec", "January", "February", "March",
				"April", "May", "June", "July", "August", "September",
				"October", "November", "December" ]
	};

	// For convenience...
	Date.prototype.format = function(mask, utc) {
		return dateFormat(this, mask, utc);
	};
})(jQuery);
